<template>
  <div>
    <div class="loading-box" v-if="loading">
      <van-loading size="24px" vertical>加载中...</van-loading>
    </div>
    <van-nav-bar
      :title="title"
      left-text="返回"
      left-arrow
      @click-left="handleToBack"
      fixed
      placeholder
      z-index="99"
    />

    <van-tabs v-model:active="active" scrollspy sticky offset-top="46" color="#1989fa">
      <van-tab title="详情">
        <div class="tab-box">
          <div class="title">比赛详情</div>
          <div class="u-type-primary-light-bg">
            <div class="u-p-20">
              <div
                :class="matchInfo.radiant_win ? 'radiant' : 'dire'"
                class="u-font-24 u-m-b-10"
              >{{ matchInfo.radiant_win ? "天辉" : "夜魇" }}胜利</div>
              <div class="u-flex u-row-center u-m-b-10">
                <div class="radiant u-font-30 u-m-r-10">{{ matchInfo.radiant_score }}</div>
                <div>
                  <div
                    class="u-content-color u-m-b-6 u-font-12"
                  >{{ getGameMode(matchInfo.game_mode) }}</div>
                  <div
                    class="u-main-color u-font-20 u-m-b-6"
                  >{{ formatGameDuration(matchInfo.duration) }}</div>
                  <div class="u-tips-color u-font-12">结束于{{ formatStartTime(matchInfo.start_time) }}</div>
                </div>
                <div class="dire u-font-30 u-m-l-10">{{ matchInfo.dire_score }}</div>
              </div>
              <van-row class="u-font-14">
                <van-col span="8">
                  <div>
                    <div class="u-m-b-10">比赛编号</div>
                    <div>{{ matchInfo.match_id }}</div>
                  </div>
                </van-col>
                <van-col span="8">
                  <div>
                    <div class="u-m-b-10">地区</div>
                    <div>{{ getRegion(matchInfo.region) }}</div>
                  </div>
                </van-col>
                <van-col span="8">
                  <div>
                    <div class="u-m-b-10">水平</div>
                    <div>{{ getSkillLevel(matchInfo.skill) }}</div>
                  </div>
                </van-col>
              </van-row>
              <div class="u-m-t-10" v-if="!matchInfo.objectives">
                <div class="u-m-b-10 u-type-warning">此录像暂未分析，有些数据暂时无法获取</div>
                <van-button type="warning" block @click="handleToRequest(matchInfo.match_id)">立即分析</van-button>
              </div>
            </div>
            <MatchTable :matchInfo="matchInfo"></MatchTable>
          </div>
        </div>
      </van-tab>
      <van-tab title="B&P" v-if="matchInfo.objectives">
        <div class="tab-box">
          <div class="title">Ban & Pick</div>
          <div class="content u-type-primary-light-bg">
            <div>
              <div
                class="u-text-left u-m-b-10 u-flex u-keep-all u-flex-wrap u-font-12"
                v-for="(item, index) in matchInfo.picks_bans"
                :key="index"
              >
                <span
                  :class="item.team === 0 ? 'radiant' : 'dire'"
                  class="u-m-r-4"
                >{{ item.team === 0 ? "天辉" : "夜魇" }}</span>
                <span
                  class="u-m-r-4"
                  :class="`player-slot-${getPickPlayerSlot(item.hero_id)}`"
                  v-if="item.is_pick"
                >{{ getPickPlayerName(item.hero_id) }}</span>
                <span class="u-m-r-4">
                  {{
                    item.is_pick ? "选择了" : "禁用了"
                  }}
                </span>
                <van-image height="20" width="36" :src="getHeroAvatar(item.hero_id)" />
                <span class="u-m-l-4">{{ getHeroName(item.hero_id) }}</span>
              </div>
            </div>
          </div>
        </div>
      </van-tab>
      <van-tab title="视野" v-if="matchInfo.objectives">
        <div class="tab-box">
          <div class="title">视野</div>
          <div class="content u-type-primary-light-bg">
            <WardMap :obsLog="obsLog" :senLog="senLog"></WardMap>
          </div>
        </div>
      </van-tab>
      <van-tab title="趋势图" v-if="matchInfo.objectives">
        <div class="tab-box">
          <div class="title">趋势图</div>
          <div class="content u-type-primary-light-bg">
            <MainLineChart
              height="300px"
              :radiantGoldAdv="matchInfo.radiant_gold_adv"
              :radiantXpAdv="matchInfo.radiant_xp_adv"
            />
            <PlayerLineChart height="500px" :players="matchInfo.players" />
            <PlayerLineChart height="500px" type="xp_t" :players="matchInfo.players" />
          </div>
        </div>
      </van-tab>
      <van-tab title="分路" v-if="matchInfo.objectives">
        <div class="tab-box">
          <div class="title">分路数据</div>
          <div class="content u-type-primary-light-bg">
            <div>
              <div
                class="u-text-left u-flex u-col-center u-row-between u-m-b-6"
                v-for="(item, index) in matchInfo.players"
                :key="index"
              >
                <div class="u-relative u-flex">
                  <van-image height="33" width="58" :src="getHeroAvatar(item.hero_id)" />
                  <div
                    :class="`player-slot-bg-${item.player_slot}`"
                    class="u-absolute u-top-0 u-right-0"
                    style="height:33px;width:4px;"
                  ></div>
                  <div class="u-m-l-4">
                    <div
                      class="u-font-12 u-m-b-8"
                      :class="`player-slot-${item.player_slot}`"
                    >{{ item.personaname || "匿名玩家" }}</div>
                    <div class="u-font-12 u-tips-color">{{ formatRankTier(item.rank_tier) }}</div>
                  </div>
                </div>
                <van-tag
                  :type="
                    getLane(item.player_slot, item.lane) === '优势路'
                      ? 'success'
                      : getLane(item.player_slot, item.lane) === '中路'
                        ? 'primary'
                        : 'danger'
                  "
                >{{ getLane(item.player_slot, item.lane) }}</van-tag>
              </div>
            </div>
          </div>
        </div>
      </van-tab>
      <!-- <van-tab title="打钱">
        <div class="tab-box">
          <div class="title">
            打钱数据
          </div>
          <div class="content u-type-primary-light-bg">
            开发中
          </div>
        </div>
      </van-tab>
      <van-tab title="神符">
        <div class="tab-box">
          <div class="title">
            控符数据
          </div>
          <div class="content u-type-primary-light-bg">
            开发中
          </div>
        </div>
      </van-tab>-->
      <van-tab title="聊天" v-if="matchInfo.objectives">
        <div class="tab-box">
          <div class="title">聊天记录</div>
          <div class="content u-type-primary-light-bg">
            <div class="chat-item" v-for="(item, index) in chatList" :key="index">
              <span class="party u-line-height-12">[{{ item.isRadiant ? "夜魇" : "天辉" }}]</span>
              <span class="time">{{ item.time }}</span>
              <van-image class="avatar" height="20" width="36" :src="getHeroAvatar(item.heroId)" />
              <span class="name" :class="`player-slot-${item.playerSlot}`">
                {{
                  item.name
                }}
              </span>
              <span class="type u-line-height-12">[所有人]：</span>
              <span class="msg" v-if="item.type === 'chatwheel'">
                {{
                  chatWheelMessage(item.content)
                }}
              </span>
              <span class="msg" v-else>{{ item.content }}</span>
            </div>
          </div>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>
<script setup>
import MainLineChart from "./components/MainLineChart/index.vue";
import PlayerLineChart from './components/PlayerLineChart/index.vue'
import MatchTable from "./components/MatchTable/index.vue";
import WardMap from "./components/WardMap/index.vue";
import { onMounted, ref, reactive } from "@vue/runtime-core";
import { useRoute, useRouter } from "vue-router";
import { getMatches, requestMatches, getRequestResult } from "@/api/match";
import {
  formatGameDuration,
  isRadiant,
  getHeroAvatar,
  getGameMode,
  formatStartTime,
  getSkillLevel,
  getRegion,
  getHeroName,
  formatRankTier,
  getLane,
} from "@/utils/dotaHelper";
import chat_wheel from "dotaconstants/build/chat_wheel.json";
import { Toast } from "vant";
const route = useRoute();
const router = useRouter();
const loading = ref(true);
const title = ref(`比赛${route.params.match_id}`);
const active = ref();
const handleToBack = () => {
  route.query.redirect ? router.replace({ name: route.query.redirect }) : router.back()
};
const chatList = ref([]);
const matchInfo = reactive({});
const obsLog = ref([]);
const senLog = ref([]);

onMounted(() => {
  loading.value = true;
  getMatches(route.params.match_id)
    .then((res) => {
      Object.assign(matchInfo, res);
      res.chat.forEach((item) => {
        const currentPlayer = matchInfo.players.find((player) => {
          return player.player_slot === item.player_slot;
        });
        const chatItem = {
          time: formatGameDuration(item.time),
          isRadiant: isRadiant(item.player_slot),
          name: currentPlayer.personaname || "匿名玩家",
          heroId: currentPlayer.hero_id,
          type: item.type,
          content: item.key,
          playerSlot: item.player_slot,
        };
        chatList.value.push(chatItem);
      });
      res.players.forEach((player) => {
        player.obs_log.forEach((obs) => {
          obsLog.value.push({
            key: obs.key,
            player_slot: obs.player_slot,
            startTime: obs.time,
            endTime: null,
            x: obs.x,
            y: obs.y,
            z: obs.z,
          });
        });
      });
      res.players.forEach((player) => {
        player.obs_left_log.forEach((obs) => {
          if (
            obsLog.value.find((item) => {
              return item.key === obs.key;
            })
          ) {
            const index = obsLog.value.findIndex((item) => {
              return item.key === obs.key;
            });
            obsLog.value[index].endTime = obs.time;
          }
        });
      });
      res.players.forEach((player) => {
        player.sen_log.forEach((obs) => {
          senLog.value.push({
            key: obs.key,
            player_slot: obs.player_slot,
            startTime: obs.time,
            endTime: null,
            x: obs.x,
            y: obs.y,
            z: obs.z,
          });
        });
      });
      res.players.forEach((player) => {
        player.sen_left_log.forEach((obs) => {
          if (
            senLog.value.find((item) => {
              return item.key === obs.key;
            })
          ) {
            const index = senLog.value.findIndex((item) => {
              return item.key === obs.key;
            });
            senLog.value[index].endTime = obs.time;
          }
        });
      });
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
});
const getPickPlayerName = (hero_id) => {
  const currentPlayer = matchInfo.players.find((player) => {
    return player.hero_id === hero_id;
  });
  return currentPlayer?.personaname || "匿名玩家";
};
const getPickPlayerSlot = (hero_id) => {
  const currentPlayer = matchInfo.players.find((player) => {
    return player.hero_id === hero_id;
  });
  return currentPlayer?.player_slot;
};
const chatWheelMessage = (content) => {
  return chat_wheel[content]
    ? chat_wheel[content].message.replace("%s1", "A Hero")
    : "[聊天轮盘]";
};
const sleep = (time) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, time);
  });
};
const handleToRequest = async (matchId) => {
  const toast = Toast.loading({
    duration: 0,
    forbidClick: true,
    message: "分析中",
  });
  const res = await requestMatches(matchId);
  let count = 0;
  while (count < 10) {
    const result = await getRequestResult(res.job.jobId);
    await sleep(2000);
    if (!result) {
      toast.message = '分析成功'
      router.go(0);
    }
    count++;
  }
  toast.message = '分析失败'
  Toast.clear();
};
</script>
<style lang="scss" scoped>
.tab-box {
  .title {
    text-align: left;
    padding: 10px;
    background-image: linear-gradient(135deg, #3c8ce7 10%, #00eaff 100%);
    color: #fff;
  }
  .content {
    padding: 10px;
    .chat-item {
      display: flex;
      flex-wrap: wrap;
      word-break: break-all;
      align-items: center;
      text-align: left;
      margin-bottom: 10px;
      row-gap: 4px;
      font-size: 14px;
      .party {
        margin-right: 4px;
      }
      .time {
        margin-right: 4px;
        font-size: 12px;
        color: rgba(0, 0, 0, 0.5);
      }
      .avatar {
        margin-right: 4px;
      }
      .name {
      }
      .type {
        margin-right: 4px;
      }
      .msg {
      }
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}
.loading-box {
  position: fixed;
  z-index: 100;
  top: 0;
  left: 0;
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
}
</style>
